import paho.mqtt.publish as publish
from paho.mqtt import client
from paho import mqtt
import time


# MQTT配置
MQTTUSERNAME = 'root'
MQTTPASSWORD = 'emdoor'
MQTTSUBTOPIC = 'lorawan/uplink'
MQTTPORT = 1883
MQTTHOST = '39.108.232.60'


def client_loop():
    mqtt_client = client.Client(client_id="{}".format(time.time()),
                               clean_session=True, userdata=None,
                               protocol=client.MQTTv31)
    mqtt_client.username_pw_set(MQTTUSERNAME, MQTTPASSWORD) # 必须设置，否则会返回「Connected with result code 4」
    userdata = {'hello':'world'}
    mqtt_client.user_data_set(userdata)
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.connect(MQTTHOST, MQTTPORT, 60)
    mqtt_client.loop_forever()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(userdata)
    print([i for i in dir(msg) if '_' not in i])
    print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
    client_loop()
